$.urlParam = function(name){
	var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
	if (results==null){
		return null;
	}
	else{
		return results[1] || 0;
	}
};


var $time=1000;
var $id=$.urlParam('id');


var $keep_alive = function(){$.ajax({
	data:"id="+$id,
	url:"ajax_attente_tour.html",
	success:function(result){
		if(result == "1"){
			location.reload();
		}
		else if(result == "0"){}
		else{
			$(".alert").html(result);	
		}
	}
});
};


$(document).ready(function(){
	setInterval($keep_alive,5000);

	$( ".jeton-dpl" ).draggable({revert: "invalid"});
	if($(".jeton-dpl").length == 0){
		$(".jeton").draggable({revert:"invalid"});	
	}
	var caseTiree = $("#caseTiree").text();
	var caseNom = ".val";
	var caseDropUp = caseNom + caseTiree;
	var caseDropDown = caseNom + caseTiree;

	while($(caseDropUp).children().length == $(caseDropUp).length){
		caseTiree++;
		caseDropUp = caseNom + caseTiree;
		if(caseTiree == 20)
			break;
	}

	while($(caseDropDown).children().length == $(caseDropDown).length){
		caseTiree--;
		caseDropDown = caseNom + caseTiree;
		if(caseTiree == 0)
			break;
	}


	$( caseDropUp ).droppable({
		accept: function(){
			if($(this).children().length < 1){
				return ".jeton-dpl";
			}
		},
		drop: function( event, ui ) {
			ui.draggable.appendTo( $(this) ).removeAttr("style").addClass("pull-right").css({
				position: "relative"
			});
			var numeroJeton = ui.draggable.text();
			var numeroCase = $(this).attr('id');
			$('#inputJeton').attr("value",numeroJeton);
			$('#inputCase').attr("value",numeroCase);
			var $parameters = "id=" +$id+"&jetonPose="+numeroJeton+"&nrCase="+numeroCase;
			$.ajax({
				url:"jouer.html",
				type:"POST",
				data:$parameters,
				success:function(data){
					if(data == "1")
						setInterval($keep_alive,$time);
					else
						$(".alert").append(data);	
				}
			});

		}
	});

	$( caseDropDown ).droppable({
		accept: function(){
			if($(this).children().length < 1){
				return ".jeton-dpl";
			}
		},
		drop: function( event, ui ) {
			ui.draggable.appendTo( $(this) ).removeAttr("style").addClass("pull-right").css({
				position: "relative"
			});
			var numeroJeton = ui.draggable.text();
			var numeroCase = $(this).attr('id');
			$('#inputJeton').attr("value",numeroJeton);
			$('#inputCase').attr("value",numeroCase);
			var $parameters = "id=" +$id+"&jetonPose="+numeroJeton+"&nrCase="+numeroCase;
			$.ajax({
				url:"jouer.html",
				type:"POST",
				data:$parameters,
				success:function(data){
					if(data == "1")
						setInterval($keep_alive,$time);
					else
						$(".alert").append(data);				
				}
			});

		}
	});

});